package com.baiduAI.body_seg;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.Button;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.baiduAI.body_seg.bean.InpaintingJson;
import com.baiduAI.body_seg.bean.JsonRootBean;
import com.baiduAI.body_seg.util.BitmapUtil;
import com.baiduAI.body_seg.util.GsonUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import rx.Observable;
import rx.Subscriber;
import rx.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity {

    private ImageView renwu;
    private ImageView yuantu;
    private ImageView beijing;
    private Button upPic;
    private final ExecutorService netThread = Executors.newCachedThreadPool();
    private Bitmap bitmap;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        yuantu = findViewById(R.id.yuantu);
        renwu = findViewById(R.id.renwu);
        beijing = findViewById(R.id.beijing);
        upPic = findViewById(R.id.uppic);
        upPic.setOnClickListener(pickPhoto);



    }

    View.OnClickListener pickPhoto = v -> {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, 1);

    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String picturePath;
        if (requestCode == 1 && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);
            cursor.close();
            if (!picturePath.isEmpty()) {
                bitmap = BitmapFactory.decodeFile(picturePath);
                yuantu.setImageBitmap(bitmap);
                operate(new File(picturePath));
            }

        }
    }

    private void operate(File file) {
        Observable.just(file)
                .map(BodySeg::body_seg)
                .map(s -> GsonUtils.fromJson(s, JsonRootBean.class))
                .map(jsonRootBean -> {
                    runOnUiThread(() -> renwu.setImageBitmap(BitmapUtil.base64ToBitmap(jsonRootBean.getForeground())));
                    List<Object> rectangle = new ArrayList<>();
                    for (int i = 0; i < jsonRootBean.getPerson_num(); i++) {
                        Map<String, Object> rectangleMap = new HashMap<>();
                        rectangleMap.put("top", (int) (jsonRootBean.getPerson_info().get(i).getTop()));
                        rectangleMap.put("left", (int) (jsonRootBean.getPerson_info().get(i).getLeft()));
                        rectangleMap.put("width", (int) (jsonRootBean.getPerson_info().get(i).getWidth()));
                        rectangleMap.put("height", (int) (jsonRootBean.getPerson_info().get(i).getHeight()));
                        rectangle.add(rectangleMap);
                    }
                    return Inpainting.inpainting(BitmapUtil.bitmapToBase64(bitmap), rectangle);
                })
                .subscribeOn(Schedulers.from(netThread))
                .observeOn(Schedulers.from(netThread))
                .subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                startBgAnim();
                                startMainAnim();
                            }
                        });
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d("TAG", "onError");
                        e.printStackTrace();
                        runOnUiThread(() -> beijing.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath())));
                    }

                    @Override
                    public void onNext(String s) {
                        InpaintingJson inpaintingJson = GsonUtils.fromJson(s, InpaintingJson.class);
                        Bitmap bitmap = BitmapUtil.base64ToBitmap(inpaintingJson.getImage());
                        runOnUiThread(() -> beijing.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath())));
                    }
                });
    }

    private void startBgAnim() {
//        float centerX = beijing.getWidth() / 2f;
//        float centerY = beijing.getHeight() / 2f;
//
//        final Rotate3dAnimation rotation = new Rotate3dAnimation(330, 360, centerX, centerY, -100, false);
//        rotation.setDuration(3000);
//        // 动画完成后保持完成的状态
//        rotation.setFillAfter(true);
//        rotation.setInterpolator(new AccelerateDecelerateInterpolator());
////        beijing.startAnimation(rotation);

        int translationY = -beijing.getWidth() / 10;
        int translationX = beijing.getHeight() / 10;
        ObjectAnimator animator3 = ObjectAnimator.ofFloat(beijing, "translationY", translationY, 0F);
        ObjectAnimator animator4 = ObjectAnimator.ofFloat(beijing, "translationX", translationX, 0F);
        ObjectAnimator animator1 = ObjectAnimator.ofFloat(beijing, "scaleY", 1.1f, 1F);
        ObjectAnimator animator2 = ObjectAnimator.ofFloat(beijing, "scaleX", 1.1f, 1F);

        AnimatorSet set = new AnimatorSet();
        set.setDuration(3000);
        set.setInterpolator(new AccelerateDecelerateInterpolator());
        set.playTogether(animator1, animator2, animator3, animator4);
        set.start();
    }

    private void startMainAnim() {

        ObjectAnimator animator1 = ObjectAnimator.ofFloat(renwu, "scaleY", 1.5f, 1F);
        ObjectAnimator animator2 = ObjectAnimator.ofFloat(renwu, "scaleX", 1.5f, 1F);

        AnimatorSet set = new AnimatorSet();
        set.setDuration(3000);
        set.setInterpolator(new AccelerateDecelerateInterpolator());
        set.playTogether(animator1,animator2);
        set.start();
    }

}